<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\model\Admin;//员工模型

class Login extends Controller
{
    public function login(Request $request)
    {
        if ($request->isGet()) {
            if (!is_file('static/Admin/dict/dict.json')) {
                $data = getables('dict');
                $this->set_php_file("static/Admin/dict/dict.json", json_encode($data));
            }
            $admin_id = session('userid');//获取管理员id
            if (!$admin_id) {
                $admin_cache = cookie('admin_cache');
                return view('login', ['admin_cache' => $admin_cache]);
            } else {
                $this->redirect('/');
            }
        } elseif ($request->isAjax()) {
            $verify = '';
            $data = request()->param();
            //对所提交的数据进行验证
            if (cookie('admin_cache') >= 3 && isset($data['verify'])) {
                if (!captcha_check($data['verify'])) {
                    return json(['status' => 0, 'msg' => lang("wrong_verification_code")]);
                }
                $verify = $data['verify'];
            }
            $lginfo = new \app\admin\model\Admin();
            //账号 密码
            $info = $lginfo->getLoginStatu($data['name'], $data['passwd'], $verify);
            return $info;
        }
    }

    //员工的修改密码
    public function editpass(Request $request)
    {
        $data = $request->param();
        $admin = new Admin();
        if ($request->isGet()) {
            return view('login/editpass');
        } elseif ($request->isAjax() && $request->isPost()) {
            $adminret = $admin->editpass($data);
            $udata["status"] = $adminret['status'];
            $udata['msg'] = $adminret['msg'];
            echo json_encode($udata);
        }
    }

    //个人资料查看
    public function personalmeans(Request $request)
    {
        $data = $request->param();
        $admin = new Admin();
        if ($request->isGet()) {
            $infodata = $admin->getadminper();
            return view('login/means', [
                'info' => $infodata,
            ]);
        } elseif ($request->isAjax() && $request->isPost()) {
            $adminret = $admin->means($data);
            $udata["status"] = $adminret['status'];
            $udata['msg'] = $adminret['msg'];
            echo json_encode($udata);
        }
    }

    //用户退出
    public function logout()
    {
        session(null);
        cookie(null);
        $this->redirect('admin/login/login');
    }

    //多文件的写入缓存文件中
    private function set_php_file($filename, $content)
    {
        $fp = fopen($filename, "w");
        fwrite($fp, $content);
        fclose($fp);
    }
}